package com.asiainfo.complier.action;

import com.asiainfo.complier.helper.FileHelper;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class JdkSettingAction {

	private String basePath;

	public JdkSettingAction(String basePath) {
		this.basePath = basePath;
	}

	/**
	 * @return
	 * @throws Exception
	 */
	public ArrayList doExecute() throws Exception {
		ArrayList jarList = new ArrayList();
		String javaBinPath = basePath + File.separator + "bin" + File.separator;
		String javaJarPath = basePath + File.separator + "lib" + File.separator;
		String javaJreJarPath = basePath + File.separator + "jre"
				+ File.separator + "lib" + File.separator;

		if (!FileHelper.isExists(javaBinPath + "java" + getExtName())) {
			throw new Exception("can't find java ");
		}
		if (!FileHelper.isExists(javaBinPath + "javac" + getExtName())) {
			throw new Exception("can't find javac ");
		}

		explorerJarFile(jarList, javaJarPath);
		explorerJarFile(jarList, javaJreJarPath);
		return jarList;
	}

	private String getExtName() {
		String osName = System.getProperty("os.name").toLowerCase();
		String extName = "";
		if (osName.indexOf("window") != -1) {
			extName = ".exe";
		}
		return extName;
	}

	/**
	 * getJavaVersion
	 * 
	 * @return
	 */
	public String getJavaVersion() {

		String javaPath = basePath + File.separator + "bin" + File.separator;
		String javaHome = javaPath + "java" + getExtName();
		if (!FileHelper.isExists(javaHome))
			return null;

		Process p = null;
		try {
			String[] cmd = new String[] { "java", "-version" };
			String[] env = new String[] { "path=" + javaPath };
			// System.out.println(javaHome);
			p = Runtime.getRuntime().exec(javaHome + " -version");
			//System.out.println(p.getInputStream());

			BufferedReader r = new BufferedReader(new InputStreamReader(
					p.getErrorStream()));

			String l = r.readLine();
			//System.out.println(l);
			int index = l.indexOf("\"");
			if (index != -1) {
				int endIndex = l.indexOf("\"", index + 1);
				if (endIndex != -1) {
					return l.substring(index + 1, endIndex);
				}
			}
			return null;
		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;

	}

	public String getJavaHome() {
		return this.basePath;
	}

	public ArrayList<String> getJarByPath(String path) {
		ArrayList<String> jarFileList = new ArrayList<String>();
		explorerJarFile(jarFileList, path);
		return jarFileList;
	}

	private void explorerJarFile(ArrayList<String> jarList, String path) {
		File file = new File(path);
		File[] fileList = file.listFiles();

		for (File f : fileList) {
			if (f.isFile()) {
				if (f.getAbsolutePath().toLowerCase().endsWith(".jar"))
					if (!jarList.contains(f.getAbsolutePath()))
						jarList.add(f.getAbsolutePath());
			}

		}
	}
}
